<template>
    <div class="main">
        <!-- 头部 -->
        <el-header>
            <div>
                <span>Vue+Element-UI增删改查</span>
            </div>
            <el-button type="info" @click="logout">退出</el-button>
        </el-header>
        
        <!-- 主体区域 -->
        <el-card>
            <el-form :inline="true" ref="searchFormRef" :model="searchForm">
                <el-form-item label="姓名" prop="search_username">
                    <el-input placeholder="姓名" v-model="searchForm.search_username"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="search_mobile">
                    <el-input placeholder="手机号" v-model="searchForm.search_mobile"></el-input>
                </el-form-item>
                <el-form-item label="状态" prop="search_mg_state">
                    <el-select v-model="searchForm.search_mg_state" placeholder="请选择状态">
                        <el-option label="启用" value="1"></el-option>
                        <el-option label="禁用" value="2"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary">查询</el-button>
                </el-form-item>
            <!-- </el-form>
            <el-form :inline="true"> -->
                <el-form-item>
                    <el-button type="info" @click="resetSearch">重置</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="warning" @click="addRow">添加</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="danger" @click="speedupData()">删除</el-button>
                </el-form-item>
            </el-form>

                <!-- 用户列表区 -->
            <el-table :data="userlist.slice((currentPage-1)*pagesize,currentPage*pagesize)" stripe @selection-change="handleSelectionChange"> 
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column type="index" prop="index"></el-table-column>
                <el-table-column label="姓名" prop="username"></el-table-column>
                <el-table-column label="手机号" prop="mobile"></el-table-column>
                <el-table-column label="邮箱" prop="email"></el-table-column>
                <el-table-column label="地址" prop="role_name"></el-table-column>
                <el-table-column label="状态" prop="mg_state"></el-table-column>
                <el-table-column label="创建日期" prop="create_date"></el-table-column>
                <el-table-column label="操作" prop="role_name" width="180px">
                    <template slot-scope="scope">
                        <!-- 编辑按钮 -->
                        <el-button type="primary" icon="el-icon-edit" size="mini" @click="handleEdit(scope.$index, scope.row)"></el-button>
                        <!-- 删除按钮 -->
                        <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDelete(scope.$index,userlist)"></el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <el-pagination
                     layout="prev, pager, next"
                     @current-change="current_change"
                     :total="total"
                     background
                    >
                  </el-pagination>
            
        </el-card>
    
<!-- 添加用户的弹窗 -->
    <el-dialog
            title="添加用户"
            :visible.sync="adddialogVisible"
            width="50%"
            @close="addDialogClosed">
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
                <el-form-item label="姓名" prop="username">
                    <el-input v-model="addForm.username"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="addForm.mobile"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addForm.email"></el-input>
                </el-form-item>
                <el-form-item label="地址" prop="role_name">
                    <el-input v-model="addForm.role_name"></el-input>
                </el-form-item>
                <el-form-item label="状态">
                    <el-select v-model="value" placeholder="请选择状态">
                        <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
            <el-button @click="adddialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addUser">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 编辑用户的弹窗 -->
        <el-dialog
            title="编辑用户"
            :visible.sync="editFormVisible"
            width="50%"
            >
            <el-form :model="editForm" :rules="addFormRules" ref="editFormRef" label-width="70px">
                <el-form-item label="姓名" prop="username">
                    <el-input v-model="editForm.username"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="editForm.mobile"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editForm.email"></el-input>
                </el-form-item>
                <el-form-item label="地址" prop="role_name">
                    <el-input v-model="editForm.role_name"></el-input>
                </el-form-item>
                <el-form-item label="状态">
                    <el-select v-model="value" placeholder="请选择状态">
                        <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
            <el-button @click="editFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="sumbitEditRow">确 定</el-button>
            </span>
        </el-dialog>


    </div>
</template>


<script>
var _index; //定义一个全局变量，以获取行数据的行号
export default{
    data(){
        //验证手机号的规则
        var checkMobile = (rule, value, callback) => {
            //验证手机号的正则表达式
            const regMobile = /^1[3|4|5|7|8][0-9]{9}$/

            if(regMobile.test(value)){
                return callback()
            }
            callback(new Error('请输入合法的手机号'))
        }

        //验证邮箱的规则
        var checkEmail = (rule,value,callback) =>{
            //验证邮箱的正则表达式
            const regEmail = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
            if(regEmail.test(value)){
                return callback()
            }
            callback(new Error('请输入合法的邮箱地址'))
        }
        return{
            total:50,//默认数据总数
            pagesize:10,//每页的数据条数
            currentPage:1,//默认开始页面
            istag: true,
            LineListSelections: [],//复选框狂选中的行
            


            //表格的数据
            userlist:[
                {
                    username:'马云',
                    mobile:'15784561262',
                    email:'474744927@qq.com',
                    role_name:'杭州',
                    mg_state:'启用',
                    create_date:'2021-6-19 19:27:47'
                },
                {
                    username:'张凯琳',
                    mobile:'13256697489',
                    email:'45646464@qq.com',
                    role_name:'北京',
                    mg_state:'禁用',
                    create_date:'2021-6-19 19:27:47'
                },
                {
                    username:'我靠',
                    mobile:'15788888888',
                    email:'88888888@qq.com',
                    role_name:'上海',
                    mg_state:'启用',
                    create_date:'2021-6-19 19:27:47'
                },
                {
                    username:'王思聪',
                    mobile:'18545567895',
                    email:'465487877@qq.com',
                    role_name:'天津',
                    mg_state:'禁用',
                    create_date:'2021-6-19 19:27:47'
                },
                {
                    username:'刘德华',
                    mobile:'13285556479',
                    email:'48754454@qq.com',
                    role_name:'成都',
                    mg_state:'启用',
                    create_date:'2021-6-19 19:27:47'
                },
                {
                    username:'许明明',
                    mobile:'13244456515',
                    email:'12345678@qq.com',
                    role_name:'浙江',
                    mg_state:'启用',
                    create_date:'2021-6-19 19:27:47'
                },
                {
                    username:'王健林',
                    mobile:'13687746589',
                    email:'8888888@qq.com',
                    role_name:'广东',
                    mg_state:'禁用',
                    create_date:'2021-6-19 19:27:47'
                }
            ],
            
            addForm:[],
            searchForm:{
                search_username:'',
                search_mobile:'',
                search_mg_state:''
            },
            editForm:[],

            
            //添加用户对话框默认关闭
            adddialogVisible: false,
            //编辑用户对话框默认关闭
            editFormVisible: false,
            //状态下拉框的数据 :  启用 禁用
            options: [
                {
                    value: '1',
                    label: '启用'
                },
                {
                    value: '2',
                    label: '禁用'
                }
            ],
            value:'',
            

            //添加表单的验证规则对象，验证
            addFormRules: {
                username:[
                    {
                        required: true,
                        message: '请输入姓名',
                        trigger: 'blur'
                    },
                    {
                        min: 2,
                        max: 20,
                        message: '姓名的长度在2-20之间',
                        trigger: 'blur'
                    }
                ],
                email: [
                    {
                        required: true,
                        message: '请输入邮箱',
                        trigger: 'blur'
                    },
                    {
                        validator: checkEmail,
                        trigger : 'blur'
                    }
                ],
                mobile: [
                    {
                        required: true,
                        message: '请输入手机号码',
                        trigger : 'blur'
                    },
                    {
                        validator: checkMobile,
                        trigger: 'blur'
                    }
                ]
            },
        }
    },
    created(){
        this.getUserList()
    },
    methods:{
        //获取所有用户
        getUserList(){
                var url = 'static/table.json';
                this.$http.get(url).then((data) =>{
                    console.log(data)
                    this.userlist = data.userlist
                }).catch((err)=>{
                    console.log(err)
                })
            },
        logout(){
            this.$router.push('/login')
        },
        //获得下拉框的文本
        selectGet(vid){
            let obj = {}
            obj = this.options.find((item)=>{
                return item.value === vid
            })
            return obj.label
        },

        getNowDate() {
				var myDate = new Date;
				var year = myDate.getFullYear(); //获取当前年
				var mon = myDate.getMonth() + 1; //获取当前月
				var date = myDate.getDate(); //获取当前日
				var hours = myDate.getHours(); //获取当前小时
				var minutes = myDate.getMinutes(); //获取当前分钟
				var seconds = myDate.getSeconds(); //获取当前秒
				var now = year + "-" + mon + "-" + date + " " + hours + ":" + minutes + ":" + seconds;
				return now;
			},


        //添加用户
        addRow(){
            this.adddialogVisible = true
            this.addForm = {
                username:'',
                mobile:'',
                email:'',
                role_name:'',
                mg_state:'',
                create_date:''
            }
        },
        //确定添加
        addUser(){
            //获取当前时间
            var date = new Date();
            this.userlist.push({
                username:this.addForm.username,
                mobile:this.addForm.mobile,
                email:this.addForm.email,
                role_name:this.addForm.role_name,
                mg_state:this.selectGet(this.value),
                create_date: this.getNowDate()
            })
            this.adddialogVisible = false
        },
        //添加用户对话框关闭后自动重置表单内容
        addDialogClosed(){
            this.$refs.addFormRef.resetFields()
        },
        
        //删除用户
        handleDelete(index,row){
            this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.userlist.splice(index, 1)
                // storage.set('tableform', this.tableform)
                this.$message({
                type: 'success',
                message: '删除成功!',
                })
            }).catch((err) => {
                this.$message({
                type: 'error',
                message: err
                })
            })
        },
        //编辑用户
        handleEdit(index, row) {
            this.editFormVisible = true;
            this.editForm = Object.assign({}, row);
            _index = index;
            // console.log(index)
            // console.log(_index)
            //取到这一栏的值，也就是明白是在那一栏进行操作，从而将编辑后的数据存到表格中
        },
        //保存编辑
        sumbitEditRow(){
            //下标 第几个用户
            var editData = _index;
            this.userlist[editData].username = this.editForm.username
            this.userlist[editData].mobile = this.editForm.mobile
            this.userlist[editData].email = this.editForm.email
            this.userlist[editData].role_name = this.editForm.role_name
            this.userlist[editData].mg_state = this.selectGet(this.value)
            this.editFormVisible = false
        },

        //重置搜索栏输入框  重置按钮事件
        resetSearch(){
            this.$refs.searchFormRef.resetFields()
        },


        
        // 批量删除方法
        speedupData() {
            console.log(this.LineListSelections)
            this.$confirm('此操作将永久删除选中的用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.userlist.splice(this.LineListSelections, this.LineListSelections.length)
                    // storage.set('tableform', this.tableform)
                    this.$message({
                    type: 'success',
                    message: '删除成功!',
                    })
            }).catch((err) => {
                this.$message({
                type: 'error',
                message: err
                })
            })
        },
        
        //切换上下页
        switchChange(){
          this.istag = !this.istag ;
          
        },

        //得到当前页
        current_change:function(currentPage){
            this.currentPage = currentPage;
        },
        created:function(){
         this.total=this.userlist.length;
      },

    //获得选中的下标
      handleSelectionChange (val) {
       this.LineListSelections = val
    },
        

                
                
    },
    mounted(){
        this.getUserList()
    }
    
}
</script>
<style scoped>
.home_container{
    height: 100%;
}
.el-header{
    background-color: #373d41;
    display: flex;
    justify-content: space-between;
    padding-left: 0;
    align-items: center;
    color: #fff;
    font-size: 20px;
}
.el-form-item{
    padding-right: 30px;
}
.el-header{
    margin-bottom: 20px;
}
.main{
    text-align: center;
}




</style>
